<?php
// +---------------------------------------------------------------------+
// | ALINEJUN    | [ WE CAN DO IT JUST THINK ]                            |
// +---------------------------------------------------------------------+
// | Licensed   | http://www.apache.org/licenses/LICENSE-2.0 )           |
// +---------------------------------------------------------------------+
// | Author     | Bigotry <3162875@qq.com>                               |
// +---------------------------------------------------------------------+
// | Repository | https://gitee.com/Bigotry/ALINEJUN                      |
// +---------------------------------------------------------------------+

namespace app\admin\controller;

use app\admin\logic\Fields;
use app\common\model\Region;
use http\Exception\BadMethodCallException;
use think\image\Exception;

/**
 * 数据控制器
 */
class Article extends AdminBase
{
    
    /**
     * 数据列表
     */
    public function articleList()
    {
       
        //存在排序数据，就去出来
        $order = 'id desc';
        if(!empty($this->param['order']) && !empty($this->param['sort'])){
            $order = $this->param['order'].' '. $this->param['sort'];
            unset($this->param['order']);
            unset($this->param['sort']);
        }
        $list= $this->logicArticle->getWhere($this->param);
        $where =  [];
        if($list){
            foreach ($list as $k=>$v){
                if($v){
                    $where['a.'.$k]=$v;
                }
            }
        }
        #获取省，市，去区县的id
        $data = $this->logicArticle->getArticleList($where, 'a.*,m.nickname,c.name as category_name', $order);
        foreach($data as $k=>&$v){
            #获取省id
            if(is_numeric($v['province'])){
                $province = $this->logicRegion->getProvinceIdByName($v['province']);
                $v['province_id'] = $province ? $province['id'] : 0;
            }

            #获取城市id
            if(is_numeric($v['city'])){
                $city = $this->logicRegion->getCityIdByName($v['province_id'],$v['city']);
                $v['city_id'] = $city ? $city['id'] : 0;
            }
            #获取区县id
            if(is_numeric($v['county'])) {
                $county = $this->logicRegion->getCountyIdByName($v['city_id'], $v['county']);
                $v['county_id'] = $county ? $county['id'] : 0;
            }
        }
        //dump($data);exit;
        //是否有修改列表名的权限
        $is_power = isPower('article/editcolname') ? 1 : 0;
        //数据显示名称列表页
        $this->assign('is_power',$is_power);
        $this->assign('list', $data);
        $this->assign('article_category_list', $this->logicArticle->getArticleCategoryList([], 'id,name', '', false));
        return $this->fetch('article_list');
    }
    
    /**
     * 数据添加
     */
    public function articleAdd()
    {
        
        $this->articleCommon();
        $this->assign('info',['province'=>'','city'=>'','county'=>'']);
        return $this->fetch('article_edit');
    }
    
    /**
     * 数据编辑
     */
    public function articleEdit()
    {
        
        $this->articleCommon();
        
        $info = $this->logicArticle->getArticleInfo(['a.id' => $this->param['id']], 'a.*,m.nickname,c.name as category_name');
        
        //!empty($info) && $info['img_ids_array'] = str2arr($info['img_ids']);
        
        $this->assign('info', $info);
        
        return $this->fetch('article_edit');
    }
    
    /**
     * 数据添加与编辑通用方法
     */
    public function articleCommon()
    {

       /* if(isset($this->param['province'])){
            if ($this->param['province']==0) {
                $this->jump([RESULT_ERROR, '请选择省份~']);exit;
            }
            $province_info = $this->logicRegion->getRegionList(['id' => $this->param['province'], 'level' => 1])->toArray();
            if($province_info){
                $this->param['province'] = $province_info[0]['name'];
            }
        }
        if(isset($this->param['city'])){
            if ($this->param['city']==0) {
                $this->jump([RESULT_ERROR, '请选择城市~']);exit;
            }
            $this->param['city'] = $this->logicRegion->getRegionList(['id' => $this->param['city'], 'level' => 2])->toArray()[0]['name'];
        }
        if(isset($this->param['county'])){
            if ($this->param['county']==0) {
                $this->jump([RESULT_ERROR, '请选择区县~']);
            }
            $this->param['county'] = $this->logicRegion->getRegionList(['id' => $this->param['county'], 'level' => 3])->toArray()[0]['name'];
        }*/
        IS_POST && $this->jump($this->logicArticle->articleEdit($this->param));

        $this->assign('article_category_list', $this->logicArticle->getArticleCategoryList([], 'id,name', '', false));
    }
    
    /**
     * 数据分类添加
     */
    public function articleCategoryAdd()
    {
        
        IS_POST && $this->jump($this->logicArticle->articleCategoryEdit($this->param));
        
        return $this->fetch('article_category_edit');
    }
    
    /**
     * 数据分类编辑
     */
    public function articleCategoryEdit()
    {
        
        IS_POST && $this->jump($this->logicArticle->articleCategoryEdit($this->param));
        
        $info = $this->logicArticle->getArticleCategoryInfo(['id' => $this->param['id']]);
        
        $this->assign('info', $info);
        
        return $this->fetch('article_category_edit');
    }
    
    /**
     * 数据分类列表
     */
    public function articleCategoryList()
    {
        
        $this->assign('list', $this->logicArticle->getArticleCategoryList());
       
        return $this->fetch('article_category_list');
    }
    
    /**
     * 数据分类删除
     */
    public function articleCategoryDel($id = 0)
    {
        
        $this->jump($this->logicArticle->articleCategoryDel(['id' => $id]));
    }
    
    /**
     * 数据状态设置
     */
    public function setStatus()
    {
        
        $this->jump($this->logicAdminBase->setStatusDel('Article', $this->param));
    }

    /**
     * 修改列表名
     */
    public function editColName()
    {
        $data = input('post.');
        if(!empty($data['id']) && !empty($data['data'])){
            $res = (new Fields())->where('id',$data['id'])->setField('name',$data['data']);
            if($res){
                $this->apiReturn(1,[],'修改成功~'); 
            }else{
                $this->apiReturn(1,[],'修改成功~');
            }
        }
    }

    public function uploadFile()
    {
        return $this->fetch('upload_file');
    }

    /***
     * 导入数据
     */
    public function importData()
    {
        $url = ROOT_PATH.'public'.str_replace('\\','/',input('param.path'));
        $url = str_replace(' ','',$url);
        $url = str_replace('picture','file',$url);
        try{
            $data = get_excel_data($url,2,0,1);
            $fields = ['name','phone','category_id','describe','operator','province','city','county','hometown','street','product','identification','update_date'];
            $list  =  [] ;
            if(empty($data)){
                $this->apiReturn(1,[],'导入失败,数据为空~');
            }
            foreach ($data as $k=>$value){

                foreach ($value as $j=>$v){
                    $list[$k][$fields[$j]] = $v;
                    $list[$k]['member_id'] = MEMBER_ID;

                    //如果存在用户分类则去分类中查找id,若没有则默认无分类
                    if($fields[$j]=='category_id') {
                        if (!empty($v)) {
                            $categroy_id = db('article_category')->where(['status' => 1, 'name' => $v])->find();
                            if($categroy_id){
                                $list[$k]['category_id'] = $categroy_id['id'];
                            }else{
                                $list[$k]['category_id'] = 1; //默认无分类
                            }

                        } else {
                            $list[$k]['category_id'] = 1; //默认无分类
                        }
                    }

                    if(empty( $list[$k])){
                        unset( $list[$k]);exit;
                    }
                }
            }
            $res = (new \app\common\model\Article())->saveAll($list);
            if($res){
                $this->apiReturn(1,[],'导入成功~');
            }else{
                $this->apiReturn(1,[],'导入失败~');
            }
        }catch (\Exception $e){
            $this->apiReturn(1,[],'导入失败~');
        }
    }

    /**
     * 导出数据
     */
    public function exportData()
    {

        if(isset($this->param['field'] ) and $this->param['search_data']){
            $where = " and a.".$this->param['field']." like '%".$this->param['search_data']."%'";
        }else{
            $where = " and 1 " ;
        }

        $sql = "select a.*,b.name as category_name from zhj_article as a left join zhj_article_category as b on a.category_id = b.id where a.status=1 and a.category_id>0 ".$where ;
        $data = db()->query($sql);

        //客户需要统一字段
        $quju_fields_list = $this->fields_list;
        $quju_fields_list[]['field'] = 'update_date';
        $quju_fields_list[]['name'] = '更新日期';
        //特殊处理，这里索引不会变可以这样处理
        $quju_fields_list[2]['field'] = 'category_name';

        $fields_name =array_column($quju_fields_list,'field');
        $fields =   implode(',',$fields_name);
        $title_name =array_column($quju_fields_list,'name');
        $title =  implode(',',$title_name);
        $file_name = '数据列表'.time();
        export_excel($title,$fields,$data,$file_name);
    }
}
